package com.tangsm.spring.boot.word.to.file.utli;

import com.aspose.words.Document;
import com.aspose.words.HeaderFooter;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.HorizontalAlignment;
import com.aspose.words.License;
import com.aspose.words.Paragraph;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.Section;
import com.aspose.words.Shape;
import com.aspose.words.ShapeType;
import com.aspose.words.VerticalAlignment;
import com.aspose.words.WrapType;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;


/**
 * 基于aspose.words实现的word文档处理工具类
 *
 * @author tangsm
 * @since 2022/02/09 13:55
 */
public class AsposeWordUtils {

    private static final String FILE_TYPE = ".doc,.docx";

    /**
     * 签名验证
     * @return 验证结果（true-通过, false-不通过）
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = AsposeWordUtils.class.getClassLoader()
                    .getResourceAsStream("license.xml");
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * word文档转pdf文档并添加自定义水印
     *
     * @param wordPath      word文档全路径
     * @param watermarkText 需要添加的水印字段
     */
    public static void wordToPdfWatermarkText(String wordPath, String watermarkText) {
        if(wordPath == null || "".equals(wordPath)) {
            System.out.println("wordPath参数不能为空");
            System.out.println("wordPath = " + wordPath + ", watermarkText = " + watermarkText);
            return;
        }

        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            System.out.println("签名验证不通过，不允许转换");
            return;
        }

        // 返回此字符串中最后一次出现指定子字符串的索引
        int index = wordPath.lastIndexOf(".");
        // 获取文件名
        String name = wordPath.substring(0, index);
        // 获取后缀
        String suffix = wordPath.substring(index);

        // 校验是否word文档
        if (!FILE_TYPE.contains(suffix)) {
            System.out.println("非word文档，不允许转换");
            return;
        }

        try {
            long old = System.currentTimeMillis();
            //新建一个pdf文档
            File file = new File(name.concat(".pdf"));
            FileOutputStream os = new FileOutputStream(file);
            //Address是将要被转化的word文档
            Document doc = new Document(wordPath);
            //为doc文档添加水印
            insertWatermarkText(doc, watermarkText);

            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            os.close();
            //转化用时
            System.out.println("word turn to pdf token：" + ((now - old) / 1000.0) + "s");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 为word文档添加水印
     *
     * @param doc           word文档模型
     * @param watermarkText 需要添加的水印字段
     * @throws Exception 异常信息
     */
    public static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
        watermark.setBehindText(true);

        //水印内容
        watermark.getTextPath().setText(watermarkText);
        //水印字体
        watermark.getTextPath().setFontFamily("宋体");
        //水印宽度
        watermark.setWidth(500);
        //水印高度
        watermark.setHeight(100);
        //旋转水印
        watermark.setRotation(-40);

        //水印颜色
        watermark.getFill().setColor(Color.lightGray);
        watermark.setStrokeColor(Color.lightGray);

        //将水印放置在页面中心
        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
        watermark.setWrapType(WrapType.NONE);
        watermark.setVerticalAlignment(VerticalAlignment.CENTER);
        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);

        // 创建一个新段落并在该段中添加水印。
        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.appendChild(watermark);

        for (Section sect : doc.getSections()) {
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
        }
        System.out.println("Watermark Set");
    }

    /**
     * 在页眉中插入水印
     *
     * @param watermarkPara 水印段落
     * @param sect          节点部分
     * @param headerType    页眉或页脚的类型
     */
    public static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) {
        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
        // 当前节中没有指定类型的头，创建它
        if (header == null) {
            header = new HeaderFooter(sect.getDocument(), headerType);
            sect.getHeadersFooters().add(header);
        }
        // 在头部插入一个水印的克隆
        header.appendChild(watermarkPara.deepClone(true));
    }
}
